﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
using System.Security.Cryptography;
using System.Web.Security;

namespace GL.Tools
{

    /// <summary>
    /// Summary description for StringUtilily
    /// </summary>
    public class StringHelper
    {
        /// <summary>
        /// 随机生成字符串源
        /// </summary>
        public const string RANDOM_STRING_SOURCE = "0123456789abcdefghijklmnopqrstuvwxyz";
        public const string RANDOM_STRING_SOURCE2 = "0123456789";
        public static Random rnd = new Random();
        /// <summary>
        /// 替换字符串
        /// </summary>
        /// <param name="src">要修改的字符串</param>
        /// <param name="pattern">要匹配的正则表达式模式</param>
        /// <param name="replacement">替换字符串</param>
        /// <returns>已修改的字符串</returns>
        public static string Replace(string src, string pattern, string replacement)
        {
            return Replace(src, pattern, replacement, RegexOptions.None);
        }

        /// <summary>
        /// 替换字符串,不区分大小写
        /// </summary>
        /// <param name="src">要修改的字符串</param>
        /// <param name="pattern">要匹配的正则表达式模式</param>
        /// <param name="replacement">替换字符串</param>
        /// <returns>已修改的字符串</returns>
        public static string ReplaceIgnoreCase(string src, string pattern, string replacement)
        {
            return Replace(src, pattern, replacement, RegexOptions.IgnoreCase);
        }

        /// <summary>
        /// 替换字符串
        /// </summary>
        /// <param name="src">要修改的字符串</param>
        /// <param name="pattern">要匹配的正则表达式模式</param>
        /// <param name="replacement">替换字符串</param>
        /// <param name="options">匹配模式</param>
        /// <returns>已修改的字符串</returns>
        public static string Replace(string src, string pattern, string replacement, RegexOptions options)
        {
            Regex regex = new Regex(pattern, options | RegexOptions.Compiled);

            return regex.Replace(src, replacement);
        }

        /// <summary>
        /// 删除字符串中指定的内容
        /// </summary>
        /// <param name="src">要修改的字符串</param>
        /// <param name="pattern">要删除的正则表达式模式</param>
        /// <returns>已删除指定内容的字符串</returns>
        public static string Drop(string src, string pattern)
        {
            return Replace(src, pattern, "");
        }

        /// <summary>
        /// 删除字符串中指定的内容,不区分大小写
        /// </summary>
        /// <param name="src">要修改的字符串</param>
        /// <param name="pattern">要删除的正则表达式模式</param>
        /// <returns>已删除指定内容的字符串</returns>
        public static string DropIgnoreCase(string src, string pattern)
        {
            return ReplaceIgnoreCase(src, pattern, "");
        }

        /// <summary>
        /// 替换字符串到数据库可输入模式
        /// </summary>
        /// <param name="src">待插入数据库的字符串</param>
        /// <returns>可插入数据库的字符串</returns>
        public static string ToSQL(string src)
        {
            if (src == null)
            {
                return null;
            }
            return Replace(src, "'", "''");
        }

        /// <summary>
        /// 替换字符中的?
        /// </summary>
        /// <param name="src">待插入数据库的字符串</param>
        /// <returns>可插入数据库的字符串</returns>
        public static string makeSql(String sql, Object[] parmars)
        {
            String[] sqls = sql.Split('?');
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < parmars.Length; i++)
            {
                String replacement = "";

                if (parmars[i].GetType() == typeof(string))
                {
                    replacement = "'" + parmars[i] + "'";
                }
                else if (parmars[i].GetType() == typeof(bool))
                {
                    bool flag = (Boolean)parmars[i];
                    if (flag)
                    {
                        replacement = "1";
                    }
                    else
                    {
                        replacement = "0";
                    }
                }
                else
                {
                    replacement = parmars[i] + "";
                }

                sb.Append(sqls[i]);
                sb.Append(replacement);

            }

            return sb.ToString(); ;
        }

        /// <summary>
        /// 去掉html内容中的指定的html标签
        /// </summary>
        /// <param name="content">html内容</param>
        /// <param name="tagName">html标签</param>
        /// <returns>去掉标签的内容</returns>
        public static string DropHtmlTag(string content, string tagName)
        {
            //去掉<tagname>和</tagname>
            return DropIgnoreCase(content, "<[/]{0,1}" + tagName + "[^\\>]*\\>");
        }

        /// <summary>
        /// 去掉html内容中全部标签
        /// </summary>
        /// <param name="content">html内容</param>
        /// <returns>去掉html标签的内容</returns>
        public static string DropHtmlTag(string content)
        {
            //去掉<*>
            return Drop(content, "<[^\\>]*>");
        }

        /// <summary>
        /// 生成随机字符串
        /// </summary>
        /// <param name="num">字符串长度</param>
        /// <returns></returns>
        public static String Random(int num)
        {
            return Random(num, true, true, true);
        }

        /// <summary>
        /// 生成随机字符串(纯数字)
        /// </summary>
        /// <param name="num">字符串长度</param>
        /// <returns></returns>
        public static String RandomNumber(int num)
        {
            return Random(num, true, false, false);
        }

        /// <summary>
        /// 生成随机字符串
        /// </summary>
        /// <param name="num">生成字符创长度</param>
        /// <param name="hasNum">是否包含数字</param>
        /// <param name="hasLower">是否包含小写</param>
        /// <param name="hasUpper">是否包含大写</param>
        /// <returns></returns>
        public static String Random(int num, bool hasNum, bool hasLower, bool hasUpper)
        {
            String numStr = "1234567890";//数字类型的字符串
            String lower = "qwertyuiopasdfghjklzxcvbnm";//小写类型的字符串
            String upper = "QWERTYUIOPASDFGHJKLZXCVBNM";//大写类型的字符串

            String str = String.Empty;
            if (hasNum)
            {
                str += numStr;
            }
            if (hasLower)
            {
                str += lower;
            }
            if (hasUpper)
            {
                str += upper;
            }

            if (String.IsNullOrEmpty(str))
            {
                return String.Empty;
            }

            //得到预生成的字符串长度
            int length = str.Length;

            Random r = new Random();
            string result = string.Empty;

            //生成一个num位长的随机字符，具体长度可以自己更改
            for (int i = 0; i < num; i++)
            {
                int m = r.Next(0, length - 1);
                string s = str.Substring(m, 1);
                result += s;
            }
            return result;
        }

        /// <summary>
        /// 生成时间戳
        /// </summary>
        /// <returns></returns>
        public static long Timestamp()
        {
            return Convert.ToInt64((DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalSeconds);
        }

        /// <summary>
        /// 判断一个数据是不是数字
        /// </summary>
        /// <param name="inputData">字符串</param>
        /// <returns>结果</returns>
        public static bool IsNumeric(string inputData)
        {
            Regex _isNumber = new Regex(@"^\d+$");
            Match m = _isNumber.Match(inputData);
            return m.Success;
        }

        /// <summary>
        /// 转换html标签为web页可见内容
        /// </summary>
        /// <param name="src"></param>
        /// <returns></returns>
        public static string EscapeHtml(string src)
        {
            if (src == null)
            {
                return null;
            }
            string s = src;
            s = Replace(s, ">", "&gt;");
            s = Replace(s, "<", "&lt;");
            return s;
        }

        /// <summary>
        /// 将字符串格式化成HTML代码
        /// </summary>
        /// <param name="str">要格式化的字符串</param>
        /// <returns>格式化后的字符串</returns>
        public static String ToHtml(string str)
        {
            if (str == null || str.Equals(""))
            {
                return str;
            }

            StringBuilder sb = new StringBuilder(str);
            sb.Replace("&", "&amp;");
            sb.Replace("<", "&lt;");
            sb.Replace(">", "&gt;");
            sb.Replace("\r\n", "<br>");
            sb.Replace("\n", "<br>");
            sb.Replace("\t", " ");
            sb.Replace(" ", "&nbsp;");
            return sb.ToString();
        }

        /// <summary>
        /// 截断字符串，并且将超过的字符换为...
        /// </summary>
        /// <param name="Str"></param>
        /// <param name="N">最大可以容纳的字符位数,一个中文占两个字符位</param>
        /// <returns></returns>
        public static string CutString(string str, int len)
        {
            if (str == null)
                return "";
            int intLen = str.Length;
            int start = 0;
            int end = intLen;
            int single = 0;
            char[] chars = str.ToCharArray();
            for (int i = 0; i < chars.Length; i++)
            {
                if (Convert.ToInt32(chars[i]) > 255)
                    start += 2;
                else
                {
                    start += 1;
                    single++;
                }
                if (start >= len)
                {

                    if (end % 2 == 0)
                    {
                        if (single % 2 == 0)
                            end = i + 1;
                        else
                            end = i;
                    }
                    else
                        end = i + 1;
                    break;
                }
            }
            string temp = str.Substring(0, end);
            if (str.Length > end)
                return temp + "...";
            else
                return temp;
        }
        public static string ReplaceChar(string str)
        {
            if (str == null)
                return "";
            return str.Replace(":", "\\:").Replace("[", "\\[").Replace("{", "\\{")
                .Replace("]", "\\]").Replace("}", "\\}").Replace("\"", "\\\"")
                .Replace("'", "\\'").Replace("/", "\\/")
                .Replace("\b", "\\b").Replace("\f", "\\f").Replace("\n", "\\n")
                .Replace("\r", "\\r").Replace("\t", "\\t");
        }
        public static string SqlSafe(string source)
        {
            source = source.Replace("'", "");
            source = source.Replace("\"", "");
            source = source.Replace("-", "");
            source = source.Replace("+", "");
            source = source.Replace("&", "");
            source = source.Replace("<", "");
            source = source.Replace(">", "");
            source = source.Replace("<>", "");
            return source;
        }
        public static string ByteArrayToString(byte[] bytes)
        {
            UTF8Encoding charset = new UTF8Encoding(true);
            return charset.GetString(bytes);
        }
        public static byte[] StringToByteArray(string str)
        {
            UTF8Encoding charset = new UTF8Encoding(true);
            return charset.GetBytes(str);
        }
        public static string StreamToString(Stream stream)
        {
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                return reader.ReadToEnd();
            }
        }
        public static Stream StringToStream(string str)
        {
            byte[] bytes = StringToByteArray(str);
            return new MemoryStream(bytes);
        }
        public static void StringWriteIntoStream(string str, Stream stream)
        {
            using (stream)
            {
                byte[] bytes = StringToByteArray(str);
                stream.Write(bytes, 0, bytes.Length);
            }
        }
        public static string MD5Encrypt(string str)
        {
            return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5").ToLower();
        }

        /// <summary> 
        /// SHA1加密字符串 
        /// </summary> 
        /// <param name="source">源字符串</param> 
        /// <returns>加密后的字符串</returns> 
        public static string SHA1(string source)
        {
            return FormsAuthentication.HashPasswordForStoringInConfigFile(source, "SHA1");
        }

        public static bool IsMobile(string mobile)
        {
            return System.Text.RegularExpressions.Regex.IsMatch(mobile, @"/^13|15|18[0-9]{9}|178|147[0-9]{8}$/");
        }

        #region 加密字符串
        /// <summary>
        /// DES密钥
        /// </summary>
        private const string KEY_64 = "ajsdjs25";//注意了，是8个字符，64位
        /// <summary>
        /// DES向量
        /// </summary>
        private const string IV_64 = "ajsdjs25";
        /// <summary>
        /// 加密DES
        /// </summary>
        /// <param name="data">需要加密的字符串</param>
        /// <returns>加密后的字符串</returns>
        public static string EncodeDES(string data)
        {
            byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64);
            byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64);
            DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
            int i = cryptoProvider.KeySize;
            MemoryStream ms = new MemoryStream();
            CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateEncryptor(byKey, byIV), CryptoStreamMode.Write);
            StreamWriter sw = new StreamWriter(cst);
            sw.Write(data);
            sw.Flush();
            cst.FlushFinalBlock();
            sw.Flush();
            return Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length);

        }
        /// <summary>
        /// 解密DES
        /// </summary>
        /// <param name="data">需要解密的字符串</param>
        /// <returns>解密后的字符串</returns>
        public static string DecodeDES(string data)
        {
            byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64);
            byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64);
            byte[] byEnc;
            try
            {
                byEnc = Convert.FromBase64String(data);
            }
            catch
            {
                return null;
            }

            DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
            MemoryStream ms = new MemoryStream(byEnc);
            CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateDecryptor(byKey, byIV), CryptoStreamMode.Read);
            StreamReader sr = new StreamReader(cst);
            return sr.ReadToEnd();
        }
        #endregion

        /// <summary>
        /// BASE64编码
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static String BASE64Encoding(String str)
        {
            byte[] bytes = Encoding.Default.GetBytes(str);
            return Convert.ToBase64String(bytes);
        }

        /// <summary>
        /// BASE64解码
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static String BASE64Decoder(String str)
        {
            byte[] outputb = Convert.FromBase64String(str);
            return Encoding.Default.GetString(outputb);
        }
    }
}
